import { defineStore } from "pinia"
import { delShopApi, getShopApi, updateShopApi } from "../api/modules/shop"
const tabBarRouter = ['pages/home/home', 'pages/cate/cate', 'pages/shop/shop', 'pages/my/my']


// 定义pinia仓库
export const ShopStore = defineStore('ShopStore', {
	state: () => ({
		// 购物车列表
		shopList: [],
		// 地址ID
		addressId: null,
	}),
	actions: {
		// 获取购物车列表【更新购物车列表】
		async updateList() {
			const { data } = await getShopApi()
			console.log(data);
			// 设置购物车默认选中状态
			data.forEach(item => (item.isCheck = true))
			this.shopList = data
			// 判断当前页面是否为tabbar页面
			const pages = getCurrentPages()
			const route = pages[pages.length - 1].route
			if (tabBarRouter.includes(route)) {
				// 设置tabbar角标
				uni.setTabBarBadge({ text: this.count + '', index: 2 })
			}
		},
		// 修改购物车数量
		async updateCount(id, count) {
			await updateShopApi({ cartItemId: id, goodsCount: count })
			const index = this.shopList.findIndex(item => item.cartItemId === id)
			// 修改商品列表中对应商品的数量
			this.shopList[index].goodsCount = count
		},
		// 删除购物车商品
		async deleteGoods(id) {
			await delShopApi(id)
			this.updateList()
		}
	},
	getters: {
		// 是否全选
		isCheckAll: state => state.shopList.filter(item => item.isCheck).length === state.shopList.length,
		// 总价   1. 筛选选中  2. 累加
		totalPrice: state => state.shopList.reduce((sum, item) => item.isCheck ? sum + item.goodsCount * item.sellingPrice: sum , 0),
		// 购物车数量
		count: state => state.shopList.length,
		// 选中商品IDs
		checkIds: state => state.shopList.filter(item => item.isCheck).map(item => item.cartItemId)
	}
})